const { Forms, Projects, User } = require('../models/index')
const { pick } = require('../util/util')

//添加报名
function addForm(params) {
  return new Promise((resolve, reject) => {
    const { project_id, user_id } = params
    // 先判断该项目是否存在
    Projects.findOne({ where: { project_id } }).then(project => {
      if (!project) {
        reject('项目不存在')
        return
      } else {
        if (project.status == 1) {
          reject('该项目已结束报名')
          return
        } else {
          // 可以报名，判断是否重复报名
          Forms.findOne({ where: { project_id, user_id } }).then(data => {
            if (data) {
              reject('已报名')
              return
            } else {
              Forms.create(
                { project_id, user_id, status: 0, reason: null } //这里status代表表单状态
              ).then(data => {
                resolve(data)
              }).catch(err => {
                reject(`添加报名失败：${err.message}`)
                logError(`添加报名失败：${err.message}`)
              })
            }
          })
        }
      }
    })
  })
}

//根据老师id获取审批单列表,联表同步获取学生信息
function getFormByAdminId(params) {
  return new Promise((resolve, reject) => {
    Forms.findAll({
      where: {

      },
      attributes: ['form_id', 'status', 'reason'],
      include: [
        {
          model: Projects, // 关联的项目表
          as: 'projectDetail', // 使用别名
          attributes: ['title', 'status', 'start_time', 'over_time', 'people_num'], // 选择要返回的字段
          where: {
            admin_id: params.admin_id
          }, // 可以在这里添加其他条件
        },
        {
          model: User, // 关联的用户表
          as: 'userDetail', // 使用别名
          attributes: ['name', 'sex', 'stu_num', 'avatar', 'faculty', 'introduction'], // 选择要返回的字段
          // where: {
          //   user_id: params.admin_id
          // }, // 可以在这里添加其他条件
        }
      ]
    }).then(data => {
      console.log(data)
      resolve(data)
    })
  })
}

//根据表单id更改状态,这里要form表连project表，因为要判断当前操作的人是否为审批人
//先表单关联用户确认身份，而后根据项目id判断人数达标没
function updateFormStatus(params) {
  return new Promise((resolve, reject) => {
    const { form_id, status, reason, admin_id } = params
    Forms.findOne({
      where: { form_id },
      include: [
        {
          model: Projects, // 关联的项目表
          as: 'projectDetail', // 使用别名
          attributes: ['project_id', 'title', 'status', 'start_time', 'over_time', 'people_num'], // 选择要返回的字段
          where: {
            admin_id: params.admin_id
          },
        }]
    }).then(data => {
      if (!data) {
        reject('表单不存在')
        return
      } else {
        if (data.status == 1 || data.status == 2) {
          reject('已审批')
        } else {
          const people_num = data.projectDetail.people_num
          const project_id = data.projectDetail.project_id
          console.log(people_num, project_id)
          // 审批
          Forms.update(
            { status, reason },
            { where: { form_id } }
          ).then(data => {
            //判断是否需要更新项目状态
            resolve(data)
            Forms.findAll(
              {
                where: {
                  project_id: project_id,
                  status: 1
                }
              }
            ).then(data => {
              console.log(data)
              if (data.length == people_num) {
                Projects.update(
                  { status: 1 },
                  { where: { project_id: project_id } }
                ).then(data => {
                  // 更新项目状态后，自动拒绝所有其他申请
                  resolve(data)
                  Forms.update({
                    status: 2,
                    reason: '人数已满'
                  },
                    {
                      where: {
                        project_id: project_id,
                        status: 0
                      }
                    }).then(data => {
                      resolve(data)
                    }
                    )
                }).catch(err => {
                  reject(`更新表单状态失败：${err.message}`)
                })
              }
            })
          }).catch(err => {
            reject(`更新表单状态失败：${err.message}`)
          })
        }
      }
    })
  })
}

// 获取我报名的项目列表
function getFormByUserId(params) {
  return new Promise((resolve, reject) => {
    Forms.findAll({
      where: {
        user_id: params.user_id
      },
      attributes: ['form_id', 'status', 'reason'],
      include: [
        {
          model: Projects, // 关联的项目表
          as: 'projectDetail', // 使用别名
          attributes: ['project_id', 'title', 'status', 'start_time', 'over_time', 'people_num'], // 选择要返回的字段
        }]
    }).then(data => {
      resolve(data)
    })
  }).catch(err => {
    reject(`获取表单失败：${err.message}`)
  })
}

// 根据项目id获取全部报名表
function getFormByProjectId(params) {
  return new Promise((resolve, reject) => {
    Forms.findAll({
      where: {
        project_id: params.project_id
      },
      attributes: ['status'],
      include: [
        {
          model: User, // 关联的项目表
          as: 'userDetail', // 使用别名
          attributes: ['name','sex','avatar','faculty','stu_num'], // 选择要返回的字段
        }]
    }).then(data => {
      resolve(data)
    }
    )
  })
}




module.exports = {
  addForm, getFormByAdminId, updateFormStatus, getFormByUserId, getFormByProjectId
}